﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .canvas-box{
            width:500px;
            height:400px;
            background-color: skyblue;
            margin:auto;
        }
        #mycanvas{
            background-color: #f40;
            border: 2px solid pink;

        }
        #dianji,#button2,#button3,#button4{
            width:80px;
            height:40px;
            font-size:16px;
        }
        #button2{
            background-color:#21E552;
        }
        #button3{
            background-color:#800080;
        }
        #button4{
            background-color:#fff;
        }
    .cancas-div2{
        margin-left:590px;
        margin-top:20px;
    }
    </style>
</head>
<body>
<div  class="canvas-box">
    <canvas id="mycanvas" width="500" height="400"></canvas>
</div>
<div class="cancas-div2">
<button onclick="move()" id="dianji">点击出现</button>
<button onclick="green()" id="button2">浅绿</button>
<button onclick="purple()" id="button3">深紫</button>
<button onclick="gray()" id="button4">白色</button>
</div>
<script>
    var c = document.getElementById("mycanvas");
    var b1 =document.getElementById("button2");
    var b2 =document.getElementById("button3");
    var b3 =document.getElementById("button4");
    var randomcolor;

    //创建一个绘制 context 对象
    var ctx = c.getContext("2d");
    var colorarry = ["#21E552","#800080","#fff"];
    var set;
    var rightnumber = 500;
    function move(){
        clearInterval(set);
        console.log(1);
        set = setInterval(function(){
            ctx.clearRect(0,0,500,400);
            if(rightnumber <= -50){
                randomcolor = Math.floor(Math.random()*3);
                ctx.fillStyle  = colorarry[randomcolor];
                rightnumber = 500;
            }

            ctx.beginPath();
            ctx.rect(rightnumber,100,50,25);
            ctx.fill();
            rightnumber-=50;
        },50);
    }

    function green(){
        if(randomcolor==0){
            
        }else{
           alert("错啦！");

         }
        }
    function purple(){
        if(randomcolor==1){
        }else{
            alert("错啦！");
        }

    }
    function gray(){
        if(randomcolor==2){
            
        }else{
            alert("错啦！");
        }
    }
</script>
</body>
</html>